#include "functions.h"

SDL_Surface *load_image(std::string filename)
{
	/* Loads an image from a file and returns an SDL_Surface object
	 * TODO: Add exception handling.
	 */

    //Temporary storage for the image that's loaded
    SDL_Surface* loadedImage = NULL;

    //The optimized image that will be used
    SDL_Surface* optimizedImage = NULL;

    //Load the image
    loadedImage = IMG_Load(filename.c_str());

    //If nothing went wrong in loading the image
    if(loadedImage != NULL)
    {
        //Create an optimized image
        optimizedImage = SDL_DisplayFormat(loadedImage);

        //Free the old image
        SDL_FreeSurface(loadedImage);

        if(optimizedImage != NULL)
        {
        	//Map the color key
        	Uint32 colorkey = SDL_MapRGB(optimizedImage->format, 200, 150, 100);

        	//Set all pixels of color colorkey to be transparent
        	SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorkey);
        }

        //Return the optimized image
        return optimizedImage;
    }
    return NULL;
}

void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
	/* Blits source SDL_Surface onto the destination SDL_Surface.
	 *
	 */
    //Make a temporary rectangle to hold the offsets
    SDL_Rect offset;

    //Give the offsets to the rectangle
    offset.x = x;
    offset.y = y;

    //Blit the surface
    SDL_BlitSurface(source, NULL, destination, &offset);
}
